// 星空动效模块 - 优化版
function initStarrySkyEffect(canvas, options = {}) {
    // 创建两个Canvas元素：一个用于缓存星空，一个用于显示
    var cacheCanvas = document.createElement("canvas");
    var displayCanvas = canvas; // 使用传入的canvas参数
    
    // 配置选项
    var config = {
        starCount: options.starCount || 8000, // 减少星星数量以提升性能
        rotationSpeed: options.rotationSpeed || 0.05, // 降低旋转速度使其更自然
        backgroundColor: options.backgroundColor || "rgba(25, 25, 85, 1)", // 深蓝色背景更适合星空
        meteorFrequency: options.meteorFrequency || 45, // 调整流星出现频率
        twinkleEnabled: options.twinkleEnabled !== undefined ? options.twinkleEnabled : true,
        galaxyEnabled: options.galaxyEnabled !== undefined ? options.galaxyEnabled : true, // 是否启用银河效果
        starSizeRange: { min: 0.3, max: 1.5 }, // 星星大小范围
        ...options
    };
    
    // 获取Canvas尺寸
    let canvasWidth = displayCanvas.offsetWidth;
    let canvasHeight = displayCanvas.offsetHeight;
    
    // 设置两个Canvas的初始尺寸
    displayCanvas.width = cacheCanvas.width = canvasWidth;
    displayCanvas.height = cacheCanvas.height = canvasHeight;
    
    // 计算最长边并扩大缓存Canvas以适应旋转
    var longSide = Math.max(canvasWidth, canvasHeight);
    cacheCanvas.width = longSide * 2.6;
    cacheCanvas.height = longSide * 2.6;
    
    // 获取绘图上下文
    var displayContext = displayCanvas.getContext('2d');
    var cacheContext = cacheCanvas.getContext('2d');
    
    // 中心点位置 - 修正为画布中心
    var centerX = canvasWidth / 2;
    var centerY = canvasHeight / 2;
    
    // 存储星星数据的数组
    var stars = [];
    // 存储流星数据的数组
    var meteors = [];
    // 动画帧数计数器
    var drawTimes = 0;
    // 累积旋转角度
    var rotationAngle = 0;
    // 动画ID，用于后续清理
    var animationId = null;
    
    // 设置画布背景
    displayContext.fillStyle = config.backgroundColor;
    displayContext.fillRect(0, 0, canvasWidth, canvasHeight);
    
    // 设置线条样式
    displayContext.lineCap = 'round';

    /**
     * 生成指定范围内的随机整数
     */
    function rand(min, max) {
        var range = max - min;
        var random = Math.random();
        var num = min + Math.round(random * range);
        return num;
    }
    
    /**
     * 创建一颗星星并添加到星星数组 - 增加闪烁相关属性
     */
    function createStar() {
        // 基于位置生成更自然的颜色分布
        var distanceFromCenter = Math.sqrt(Math.pow(rand(-cacheCanvas.width/2, cacheCanvas.width/2), 2) + 
                                          Math.pow(rand(-cacheCanvas.height/2, cacheCanvas.height/2), 2));
        var maxDistance = Math.sqrt(Math.pow(cacheCanvas.width/2, 2) + Math.pow(cacheCanvas.height/2, 2));
        var distanceFactor = distanceFromCenter / maxDistance;
        
        // 星星颜色变化：中心区域偏蓝白色，边缘区域可能呈现淡黄色调
        var r, g, b;
        if (Math.random() > 0.8) { // 20%的概率是较亮的蓝白色星星
            r = rand(220, 255);
            g = rand(230, 255);
            b = rand(250, 255);
        } else if (Math.random() > 0.85) { // 15%的概率是淡黄色星星
            r = rand(230, 255);
            g = rand(220, 255);
            b = rand(180, 220);
        } else { // 65%的概率是普通星星
            r = rand(180, 255);
            g = rand(190, 255);
            b = rand(210, 255);
        }
        
        // 根据大小设置不同的亮度和闪烁特性
        var size = Math.random() * (config.starSizeRange.max - config.starSizeRange.min) + config.starSizeRange.min;
        var brightnessFactor = size / config.starSizeRange.max;
        
        // 较大的星星更亮且闪烁更明显
        var baseOpacity = Math.min(1, brightnessFactor * (Math.random() * 0.6 + 0.4) + 0.2);
        var twinkleAmount = brightnessFactor * (Math.random() * 0.3 + 0.15);
        var twinkleSpeed = Math.random() * 0.06 + 0.01; // 调整闪烁速度范围
        var twinklePhase = Math.random() * Math.PI * 2;
        
        // 添加光晕效果标志
        var hasGlow = size > 1.2 && Math.random() > 0.5;
        
        stars.push({
            x: rand(-cacheCanvas.width, cacheCanvas.width),
            y: rand(-cacheCanvas.height, cacheCanvas.height),
            size: size,
            color: { r: r, g: g, b: b },
            baseOpacity: baseOpacity,
            twinkleAmount: twinkleAmount,
            twinkleSpeed: twinkleSpeed,
            twinklePhase: twinklePhase,
            currentOpacity: baseOpacity,
            hasGlow: hasGlow,
            distanceFactor: distanceFactor
        });
    }
    
    /**
     * 根据RGB和透明度生成颜色字符串
     */
    function rgbToColor(r, g, b, a) {
        return "rgba(" + r + "," + g + "," + b + "," + a + ")";
    }
    
    /**
     * 更新星星的透明度，实现闪烁效果
     */
    function updateStars() {
        if (!config.twinkleEnabled) return;
        
        for (var i = 0; i < stars.length; i++) {
            var star = stars[i];
            // 使用正弦函数创建平滑的闪烁效果
            star.twinklePhase += star.twinkleSpeed;
            star.currentOpacity = star.baseOpacity + Math.sin(star.twinklePhase) * star.twinkleAmount;
            // 确保透明度在合理范围内
            star.currentOpacity = Math.max(0, Math.min(1, star.currentOpacity));
        }
    }
    
    /**
     * 绘制银河效果
     */
    function drawGalaxy() {
        if (!config.galaxyEnabled) return;
        
        // 创建径向渐变作为银河核心
        var gradient = cacheContext.createRadialGradient(
            0, 0, 0,
            0, 0, Math.max(cacheCanvas.width, cacheCanvas.height) * 0.4
        );
        
        // 添加渐变颜色停止点
        gradient.addColorStop(0, "rgba(100, 100, 150, 0.15)");
        gradient.addColorStop(0.3, "rgba(80, 80, 120, 0.08)");
        gradient.addColorStop(0.7, "rgba(60, 60, 100, 0.03)");
        gradient.addColorStop(1, "rgba(0, 0, 0, 0)");
        
        // 绘制银河核心区域
        cacheContext.fillStyle = gradient;
        cacheContext.beginPath();
        cacheContext.arc(0, 0, Math.max(cacheCanvas.width, cacheCanvas.height) * 0.5, 0, Math.PI * 2);
        cacheContext.fill();
        
        // 绘制几个不规则的星云带
        for (var i = 0; i < 3; i++) {
            var angle = (i / 3) * Math.PI * 2;
            var radius = Math.max(cacheCanvas.width, cacheCanvas.height) * 0.3;
            var x = Math.cos(angle) * radius * 0.5;
            var y = Math.sin(angle) * radius * 0.5;
            
            cacheContext.fillStyle = "rgba(120, 120, 160, " + (0.02 + Math.random() * 0.03) + ")";
            cacheContext.beginPath();
            cacheContext.arc(x, y, radius * (0.4 + Math.random() * 0.3), 0, Math.PI * 2);
            cacheContext.fill();
        }
    }
    
    /**
     * 在缓存Canvas上绘制所有星星 - 使用更新后的透明度
     */
    function drawStar() {
        // 先绘制银河效果
        drawGalaxy();
        
        // 分离星星以优化绘制
        var smallStars = [];
        var largeStars = [];
        
        // 分类星星
        for (var i = 0; i < stars.length; i++) {
            if (stars[i].size < 0.8) {
                smallStars.push(stars[i]);
            } else {
                largeStars.push(stars[i]);
            }
        }
        
        // 先绘制小的星星
        for (var i = 0; i < smallStars.length; i++) {
            var star = smallStars[i];
            cacheContext.beginPath();
            cacheContext.arc(star.x, star.y, star.size, 0, Math.PI * 2, true);
            cacheContext.fillStyle = rgbToColor(
                star.color.r, 
                star.color.g, 
                star.color.b, 
                star.currentOpacity
            );
            cacheContext.fill();
        }
        
        // 再绘制大的星星，添加更复杂的效果
        for (var i = 0; i < largeStars.length; i++) {
            var star = largeStars[i];
            
            // 如果星星有光晕效果，先绘制光晕
            if (star.hasGlow) {
                cacheContext.beginPath();
                cacheContext.arc(star.x, star.y, star.size * 2.5, 0, Math.PI * 2, true);
                cacheContext.fillStyle = rgbToColor(
                    star.color.r, 
                    star.color.g, 
                    star.color.b, 
                    star.currentOpacity * 0.15
                );
                cacheContext.fill();
            }
            
            // 绘制主星
            cacheContext.beginPath();
            cacheContext.arc(star.x, star.y, star.size, 0, Math.PI * 2, true);
            cacheContext.fillStyle = rgbToColor(
                star.color.r, 
                star.color.g, 
                star.color.b, 
                star.currentOpacity
            );
            cacheContext.fill();
            
            // 为较大的星星添加核心亮点
            if (star.size > 1) {
                cacheContext.beginPath();
                cacheContext.arc(star.x, star.y, star.size * 0.3, 0, Math.PI * 2, true);
                cacheContext.fillStyle = "rgba(255, 255, 255, " + star.currentOpacity * 0.8 + ")";
                cacheContext.fill();
            }
        }
    }
    
    /**
     * 将缓存Canvas的内容绘制到显示Canvas上
     * 修复绘制位置，确保星空完全覆盖可见区域
     */
    function drawFromCache() {
        // 计算适当的偏移，确保即使旋转后，星空也能完全覆盖画布
        // 由于我们已经将原点平移到画布中心，这里需要偏移缓存画布的一半大小
        var offsetX = -cacheCanvas.width / 2;
        var offsetY = -cacheCanvas.height / 2;
        displayContext.drawImage(cacheCanvas, offsetX, offsetY);
    }
    
    /**
     * 创建一颗流星
     */
    function createMeteor() {
        // 随机选择流星的进入方向
        var direction = Math.random();
        var startX, startY, angle;
        
        if (direction < 0.7) { // 70%概率从左侧进入
            startX = -100;
            startY = Math.random() * (canvasHeight + 200) - 100;
            angle = Math.PI / 6 + Math.random() * Math.PI / 6; // 30-60度角
        } else if (direction < 0.9) { // 20%概率从顶部进入
            startX = Math.random() * (canvasWidth + 200) - 100;
            startY = -100;
            angle = Math.PI / 3 + Math.random() * Math.PI / 6; // 60-90度角
        } else { // 10%概率从左侧上方斜向进入
            startX = -100;
            startY = -100;
            angle = Math.PI / 4 + Math.random() * Math.PI / 8; // 45-67.5度角
        }
        
        // 根据角度计算流星的速度分量
        var speed = Math.random() * 8 + 3; // 3-11的速度范围
        var speedX = Math.cos(angle) * speed;
        var speedY = Math.sin(angle) * speed;
        
        // 流星的特性
        var length = Math.random() * 400 + 200; // 流星长度
        var thickness = Math.random() * 1 + 0.5; // 流星粗细
        var alpha = Math.random() * 0.4 + 0.6; // 透明度
        var life = Math.floor(Math.random() * 40) + 30; // 生命周期30-70帧
        
        // 添加颜色变化
        var colorType = Math.random();
        var color;
        if (colorType < 0.6) { // 60%普通白色流星
            color = { r: 255, g: 255, b: 255 };
        } else if (colorType < 0.8) { // 20%蓝白色流星
            color = { r: 220, g: 230, b: 255 };
        } else { // 20%黄白色流星
            color = { r: 255, g: 240, b: 220 };
        }
        
        meteors.push({
            x: startX,
            y: startY,
            length: length,
            speedX: speedX,
            speedY: speedY,
            thickness: thickness,
            alpha: alpha,
            life: life,
            maxLife: life,
            color: color,
            angle: angle
        });
    }
    
    /**
     * 更新流星的位置和状态
     */
    function updateMeteors() {
        for (var i = meteors.length - 1; i >= 0; i--) {
            var meteor = meteors[i];
            
            // 更新位置
            meteor.x += meteor.speedX;
            meteor.y += meteor.speedY;
            
            // 更新生命周期
            meteor.life--;
            
            // 计算透明度衰减，前半段保持亮度，后半段逐渐淡出
            var lifeRatio = meteor.life / meteor.maxLife;
            if (lifeRatio > 0.5) {
                meteor.alpha = 0.8; // 保持亮度
            } else {
                meteor.alpha = lifeRatio * 1.6; // 逐渐淡出
            }
            
            // 当流星飞出画布时移除
            if (meteor.life <= 0 || 
                meteor.x > canvasWidth + 100 || 
                meteor.y > canvasHeight + 100) {
                meteors.splice(i, 1);
            }
        }
    }
    
    /**
     * 绘制所有流星
     */
    function drawMeteors() {
        for (var i = 0; i < meteors.length; i++) {
            var meteor = meteors[i];
            
            // 保存当前状态
            displayContext.save();
            
            // 计算流星尾迹的渐变色
            var gradient = displayContext.createLinearGradient(
                meteor.x, meteor.y,
                meteor.x - meteor.length * Math.cos(meteor.angle),
                meteor.y - meteor.length * Math.sin(meteor.angle)
            );
            
            // 添加渐变颜色停止点
            gradient.addColorStop(0, rgbToColor(meteor.color.r, meteor.color.g, meteor.color.b, meteor.alpha * 1.2));
            gradient.addColorStop(0.1, rgbToColor(meteor.color.r, meteor.color.g, meteor.color.b, meteor.alpha));
            gradient.addColorStop(0.5, rgbToColor(meteor.color.r, meteor.color.g, meteor.color.b, meteor.alpha * 0.5));
            gradient.addColorStop(1, rgbToColor(meteor.color.r, meteor.color.g, meteor.color.b, 0));
            
            // 绘制流星尾迹
            displayContext.strokeStyle = gradient;
            displayContext.lineWidth = meteor.thickness;
            displayContext.lineCap = 'round';
            displayContext.lineJoin = 'round';
            
            // 绘制主尾迹
            displayContext.beginPath();
            displayContext.moveTo(meteor.x, meteor.y);
            displayContext.lineTo(
                meteor.x - meteor.length * Math.cos(meteor.angle),
                meteor.y - meteor.length * Math.sin(meteor.angle)
            );
            displayContext.stroke();
            
            // 绘制流星头部的明亮核心
            displayContext.beginPath();
            displayContext.arc(meteor.x, meteor.y, meteor.thickness * 1.5, 0, Math.PI * 2);
            displayContext.fillStyle = "rgba(255, 255, 255, " + meteor.alpha * 1.5 + ")";
            displayContext.fill();
            
            // 添加光晕效果
            displayContext.beginPath();
            displayContext.arc(meteor.x, meteor.y, meteor.thickness * 3, 0, Math.PI * 2);
            displayContext.fillStyle = "rgba(255, 255, 255, " + meteor.alpha * 0.2 + ")";
            displayContext.fill();
            
            // 绘制一些粒子效果增加真实感
            if (Math.random() > 0.7) {
                var particleCount = Math.floor(Math.random() * 3) + 1;
                for (var p = 0; p < particleCount; p++) {
                    var offsetDistance = (Math.random() * 0.5 + 0.3) * meteor.length;
                    var offsetX = meteor.x - offsetDistance * Math.cos(meteor.angle);
                    var offsetY = meteor.y - offsetDistance * Math.sin(meteor.angle);
                    var particleSize = Math.random() * 1 + 0.5;
                    
                    displayContext.beginPath();
                    displayContext.arc(offsetX, offsetY, particleSize, 0, Math.PI * 2);
                    displayContext.fillStyle = "rgba(255, 255, 255, " + (meteor.alpha * 0.5 * Math.random()) + ")";
                    displayContext.fill();
                }
            }
            
            // 恢复状态
            displayContext.restore();
        }
    }
    
    /**
     * 旋转画布
     */
    function rotateCanvas(degrees) {
        displayContext.rotate(degrees * Math.PI / 180);
    }
    
    /**
     * 动画主循环
     */
    function loop() {
        // 步骤1: 重置整个变换矩阵并绘制背景
        displayContext.setTransform(1, 0, 0, 1, 0, 0);
        displayContext.fillStyle = config.backgroundColor;
        displayContext.fillRect(0, 0, canvasWidth, canvasHeight);
        
        // 步骤2: 应用平移到画布中心
        displayContext.translate(centerX, centerY);
        
        // 步骤3: 累积旋转角度并应用旋转 - 这是旋转效果的关键
        rotationAngle += config.rotationSpeed;
        rotationAngle = rotationAngle % 360;
        rotateCanvas(rotationAngle);
        
        // 步骤4: 更新并绘制星星 - 优化性能：不需要每帧都重新绘制所有星星到缓存
        updateStars();
        
        // 每5帧才重新绘制到缓存Canvas，提升性能
        if (drawTimes % 5 === 0) {
            cacheContext.clearRect(0, 0, cacheCanvas.width, cacheCanvas.height);
            drawStar();
        }
        
        // 从缓存Canvas绘制星星到显示Canvas
        drawFromCache();
        
        // 步骤5: 处理流星效果
        // 随机生成流星
        if (drawTimes % config.meteorFrequency === 0) {
            createMeteor();
        }
        // 更新流星位置
        updateMeteors();
        
        // 保存当前变换状态
        displayContext.save();
        // 重置变换，以便直接在屏幕坐标系绘制流星
        displayContext.setTransform(1, 0, 0, 1, 0, 0);
        // 绘制流星
        drawMeteors();
        // 恢复之前的变换状态
        displayContext.restore();
        
        // 增加帧数计数
        drawTimes++;
        
        // 继续下一帧动画
        animationId = requestAnimationFrame(loop);
    }
    
    /**
     * 清理函数，用于移除事件监听器和停止动画
     */
    function cleanup() {
        if (animationId) {
            cancelAnimationFrame(animationId);
            animationId = null;
        }
        
        // 移除窗口大小变化的监听器
        window.removeEventListener('resize', handleResize);
        
        // 清空画布
        if (displayContext) {
            displayContext.clearRect(0, 0, canvasWidth, canvasHeight);
        }
        
        // 清空星星和流星数组
        stars = [];
        meteors = [];
        
        console.log('Starry sky effect cleaned up');
    }
    
    /**
     * 处理窗口大小变化
     */
    function handleResize() {
        // 获取新的Canvas尺寸
        canvasWidth = displayCanvas.offsetWidth;
        canvasHeight = displayCanvas.offsetHeight;
        
        // 更新Canvas尺寸
        displayCanvas.width = canvasWidth;
        displayCanvas.height = canvasHeight;
        
        // 重新计算中心点
        centerX = canvasWidth / 2;
        centerY = canvasHeight / 2;
        
        // 更新缓存Canvas尺寸
        var longSide = Math.max(canvasWidth, canvasHeight);
        cacheCanvas.width = longSide * 2.2; // 稍微缩小缓存Canvas以提升性能
        cacheCanvas.height = longSide * 2.2;
        
        // 重新生成星星以适应新的尺寸
        stars = [];
        var starCount = config.starCount;
        while (starCount--) {
            createStar();
        }
        
        // 强制重绘画布
        cacheContext.clearRect(0, 0, cacheCanvas.width, cacheCanvas.height);
        drawStar();
    }
    
    // 注册窗口大小变化事件
    window.addEventListener('resize', handleResize);
    
    // 创建星星
    var starCount = config.starCount;
    while (starCount--) {
        createStar();
    }
    
    // 绘制所有星星到缓存Canvas
    drawStar();
    
    // 开始动画
    loop();
    
    // 返回清理函数，以便外部调用停止动画
    return cleanup;
}

// 暴露函数到全局作用域
window.initStarrySkyEffect = initStarrySkyEffect;